#!/usr/bin/python
# -*- coding: UTF-8 -*-

# @author huanghm
# @date 2021-12-12

#########python2.7 配置文件环境变量替换占位符
##使用方法，启动程序，并跟参数输入的文件（相对路径或绝对路径）
##类似SpringBoot配置文件环境变量占位符写法，匹配格式：^\$\{[0-9A-Z_]+:{0,1}[0-9a-zA-Z_/\-:.]+\}$
##eg:  database.url=jdbc.mysql://${MYSQL_HOST:127.0.0.1}:${MYSQL_PORT:3306}/demo
##     database.username=${MYSQL_USERNAME:root}
##     database.password=${MYSQL_PASSWORD:123456}

import re
import os
import sys
import codecs

#程序输入参数验证
if len(sys.argv) < 2 :
  print('usage : python '+sys.argv[0]+' <tpl_dir>')
  exit(-1)
#输入文件
listdir = sys.argv[1]
#文件验证
if not os.path.exists(listdir) : 
  print('Error : path '+listdir+' is not exist!')
  exit(-1)
if not os.path.isdir(listdir) : 
  print('Error : path '+listdir+' is not dir!')
  exit(-1)
  
  

def searchdir(root) : 
  items = os.listdir(root)
  for item in items :
    path = os.path.join(root,item)
    if os.path.isdir(path) :
      print('dir : ',path)
      searchdir(path)
    else:
      if item.endswith('.tpl') :
        genfile(path)
        print('file : ',path)


envfile = sys.argv[2]
envdict = {}
with codecs.open(envfile, 'r', encoding='utf-8') as f :
  for line in f.readlines() :
    line = line.strip('\n')
    items = line.split('=')
    envdict[items[0]] = items[1]
    print envdict[items[0]]
  

#正则表达式 ${ENV_KEY:value}
pattern = re.compile(r'\$\{[0-9A-Z_]+:{0,1}[0-9a-zA-Z_/\-:.]+\}')

#环境变量值替换函数
def envval(str) :
  item = str.replace('${','')
  item = item.replace('}','').split(':',1) #split第一个':'
  val = envdict.get(item[0],item[1])

  print('update config : '+str+' => '+val)
  return val

def envval2(str) :
  item = str.replace('${','')
  item = item.replace('}','').split(':',1) #split第一个':'
  val = os.environ.get(item[0])
  if not val :
    val = item[1]

  print('update config : '+str+' => '+val)
  return val
  
def genfile(tplfile) :
  newfile = tplfile.replace('.tpl','')
  print('update config begin...  file:',tplfile)
  #正则表达式查找替换
  with codecs.open(newfile, 'w', encoding='utf-8') as tmp :
    with codecs.open(tplfile, 'r', encoding='utf-8') as f :
      for line in f.readlines() :
        line = line.strip('\n')
        result = pattern.finditer(line) #匹配检索
        for item in result :
          val = envval(item.group())
          line = line.replace(item.group(),val)
        tmp.write(line+'\n')
  print('update config finish!  new file:',newfile)

searchdir(listdir)
